/**
 * 语言评审页面
 */

import React, { useState, useMemo } from 'react';
import { Typography, Steps, Card, Table, Button, Input, Space, Tag, Modal, Statistic, Alert, Tooltip, message } from 'antd';
import { 
  CheckCircleOutlined, 
  ExclamationCircleOutlined, 
  EditOutlined, 
  EyeOutlined, 
  SearchOutlined,
  DownloadOutlined,
  ArrowLeftOutlined,
  FileTextOutlined,
  GlobalOutlined,
  CodeOutlined,
  CopyOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import styled from 'styled-components';
import { themeConfig } from '../theme/themeConfig';
import { Button as CustomButton } from '../components/ui/Button';
import { useLanguageState } from '../store/appStore';
import { downloadAllFilesAsZip } from '../utils/fileUtils';
import { generateDartFileContentForDocs } from '../utils/languageUtils';
import { LanguageFile } from '../types';

const { Title, Paragraph, Text } = Typography;
const { Step } = Steps;
const { Search, TextArea } = Input;

const PageContainer = styled.div`
  min-height: 100vh;
  background-color: ${themeConfig.colors.background};
  padding: ${themeConfig.spacing.xl};
`;

const ContentContainer = styled.div`
  max-width: 1400px;
  margin: 0 auto;
`;

const HeaderSection = styled.div`
  text-align: center;
  margin-bottom: ${themeConfig.spacing.xxl};
`;

const MainTitle = styled(Title)`
  color: ${themeConfig.colors.text} !important;
  margin-bottom: ${themeConfig.spacing.md} !important;
`;

const SubTitle = styled(Paragraph)`
  color: ${themeConfig.colors.textSecondary} !important;
  font-size: ${themeConfig.typography.fontSize.body} !important;
  margin-bottom: 0 !important;
`;

const StepsContainer = styled.div`
  margin-bottom: ${themeConfig.spacing.xxl};
  
  .ant-steps-item-process .ant-steps-item-icon {
    background-color: ${themeConfig.colors.primary};
    border-color: ${themeConfig.colors.primary};
  }
  
  .ant-steps-item-finish .ant-steps-item-icon {
    background-color: ${themeConfig.colors.primary};
    border-color: ${themeConfig.colors.primary};
  }
`;

const ReviewCard = styled(Card)`
  margin-bottom: ${themeConfig.spacing.xl};
  
  .ant-card-head {
    border-bottom: 2px solid ${themeConfig.colors.primary};
  }
`;

const StatisticContainer = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: ${themeConfig.spacing.lg};
  margin-bottom: ${themeConfig.spacing.lg};
`;

const ActionSection = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: ${themeConfig.spacing.lg};
  gap: ${themeConfig.spacing.md};
`;

const LanguageTableContainer = styled.div`
  .ant-table-thead > tr > th {
    background-color: ${themeConfig.colors.backgroundLight};
    border-bottom: 2px solid ${themeConfig.colors.primary};
    font-weight: ${themeConfig.typography.fontWeight.medium};
  }
  
  .ant-table-tbody > tr:hover > td {
    background-color: #FFF2E8;
  }
`;

const TranslationModal = styled(Modal)`
  .ant-modal-header {
    background-color: ${themeConfig.colors.primary};
    color: white;
  }
  
  .ant-modal-title {
    color: white;
  }
`;

interface ReviewPageProps {
  onBack: () => void;
  onProceed: () => void;
  onEditLanguage?: (languageCode: string) => void;
}

export const ReviewPage: React.FC<ReviewPageProps> = ({ onBack, onProceed, onEditLanguage }) => {
  const { languageFiles, detectionReport } = useLanguageState();
  const [selectedLanguage, setSelectedLanguage] = useState<LanguageFile | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [isJsonModalVisible, setIsJsonModalVisible] = useState(false);
  const [jsonEditingLanguage, setJsonEditingLanguage] = useState<LanguageFile | null>(null);
  const [jsonText, setJsonText] = useState<string>('');
  const [jsonError, setJsonError] = useState<string>('');

  // 获取语言名称
  const getLanguageName = (code: string): string => {
    const languageNames: Record<string, string> = {
      'zh': '中文',
      'en': 'English',
      'ar': 'العربية',
      'cs': 'Čeština',
      'da': 'Dansk',
      'de': 'Deutsch',
      'el': 'Ελληνικά',
      'es': 'Español',
      'fa': 'فارسی',
      'fi': 'Suomi',
      'fr': 'Français',
      'ga': 'Gaeilge',
      'he': 'עברית',
      'hr': 'Hrvatski',
      'hu': 'Magyar',
      'it': 'Italiano',
      'ja': '日本語',
      'ko': '한국어',
      'nb': 'Norsk',
      'pl': 'Polski',
      'pt': 'Português',
      'ro': 'Română',
      'ru': 'Русский',
      'sk': 'Slovenčina',
      'sv': 'Svenska',
      'th': 'ไทย',
      'tr': 'Türkçe',
      'uk': 'Українська',
      'vi': 'Tiếng Việt'
    };
    return languageNames[code] || code.toUpperCase();
  };

  // 获取语言状态
  const getLanguageStatus = (code: string) => {
    const hasConflicts = detectionReport?.conflicts.some(conflict => 
      conflict.languages.includes(code)
    ) || false;
    
    const hasMissing = detectionReport?.conflicts.some(conflict => 
      conflict.type === 'missing' && conflict.languages.includes(code)
    ) || false;
    
    if (hasConflicts && hasMissing) {
      return { status: 'error', icon: <ExclamationCircleOutlined />, text: '有冲突和缺失', color: themeConfig.colors.error };
    } else if (hasConflicts) {
      return { status: 'warning', icon: <ExclamationCircleOutlined />, text: '有冲突', color: themeConfig.colors.warning };
    } else if (hasMissing) {
      return { status: 'warning', icon: <ExclamationCircleOutlined />, text: '有缺失', color: themeConfig.colors.warning };
    } else {
      return { status: 'success', icon: <CheckCircleOutlined />, text: '正常', color: themeConfig.colors.success };
    }
  };

  // 过滤语言文件
  const filteredLanguageFiles = useMemo(() => {
    if (!searchText) return languageFiles;
    
    return languageFiles.filter(file => 
      file.language.toLowerCase().includes(searchText.toLowerCase()) ||
      file.code.toLowerCase().includes(searchText.toLowerCase()) ||
      getLanguageName(file.code).toLowerCase().includes(searchText.toLowerCase())
    );
  }, [languageFiles, searchText]);

  // 统计信息
  const stats = useMemo(() => {
    const totalLanguages = languageFiles.length;
    const totalKeys = new Set<string>();
    let totalTranslations = 0;
    let emptyTranslations = 0;
    let languagesWithIssues = 0;

    languageFiles.forEach(file => {
      Object.keys(file.data).forEach(key => totalKeys.add(key));
      Object.values(file.data).forEach(value => {
        if (value && value.trim() !== '') {
          totalTranslations++;
        } else {
          emptyTranslations++;
        }
      });
      
      const status = getLanguageStatus(file.code);
      if (status.status !== 'success') {
        languagesWithIssues++;
      }
    });

    return {
      totalLanguages,
      totalKeys: totalKeys.size,
      totalTranslations,
      emptyTranslations,
      languagesWithIssues,
      completionRate: totalKeys.size > 0 ? (totalTranslations / (totalKeys.size * totalLanguages)) * 100 : 0
    };
  }, [languageFiles]);

  // 表格列定义
  const columns = [
    {
      title: '语言',
      dataIndex: 'language',
      key: 'language',
      width: 120,
      render: (_: any, record: LanguageFile) => (
        <Space>
          <GlobalOutlined style={{ color: themeConfig.colors.primary }} />
          <div>
            <div style={{ fontWeight: themeConfig.typography.fontWeight.medium }}>
              {getLanguageName(record.code)}
            </div>
            <Tag color={themeConfig.colors.primary} style={{ fontSize: '12px', margin: 0 }}>
              {record.code}
            </Tag>
          </div>
        </Space>
      ),
    },
    {
      title: '翻译项数量',
      dataIndex: 'translations',
      key: 'translations',
      width: 120,
      render: (_: any, record: LanguageFile) => (
        <Statistic
          value={Object.keys(record.data).length}
          valueStyle={{ fontSize: '16px', color: themeConfig.colors.text }}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (_: any, record: LanguageFile) => {
        const status = getLanguageStatus(record.code);
        return (
          <Space>
            <span style={{ color: status.color }}>
              {status.icon}
            </span>
            <span style={{ color: status.color, fontSize: '12px' }}>
              {status.text}
            </span>
          </Space>
        );
      },
    },
    {
      title: '完成度',
      dataIndex: 'completion',
      key: 'completion',
      width: 120,
      render: (_: any, record: LanguageFile) => {
        const totalKeys = Object.keys(record.data).length;
        const filledKeys = Object.values(record.data).filter(value => value && value.trim() !== '').length;
        const completionRate = totalKeys > 0 ? (filledKeys / totalKeys) * 100 : 0;
        
        return (
          <div>
            <div style={{ fontSize: '14px', fontWeight: themeConfig.typography.fontWeight.medium }}>
              {completionRate.toFixed(1)}%
            </div>
            <div style={{ 
              width: '100%', 
              height: '4px', 
              backgroundColor: themeConfig.colors.border,
              borderRadius: '2px',
              overflow: 'hidden'
            }}>
              <div style={{
                width: `${completionRate}%`,
                height: '100%',
                backgroundColor: completionRate === 100 ? themeConfig.colors.success : 
                                completionRate >= 80 ? themeConfig.colors.warning : themeConfig.colors.error,
                transition: 'width 0.3s ease'
              }} />
            </div>
          </div>
        );
      },
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_: any, record: LanguageFile) => (
        <Space>
          <Tooltip title="查看翻译内容">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => {
                setSelectedLanguage(record);
                setIsModalVisible(true);
              }}
              style={{ color: themeConfig.colors.primary }}
            >
              查看
            </Button>
          </Tooltip>
          <Tooltip title="编辑翻译">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => {
                if (onEditLanguage) {
                  onEditLanguage(record.code);
                }
              }}
              style={{ color: themeConfig.colors.warning }}
            >
              编辑
            </Button>
          </Tooltip>
          <Tooltip title="JSON编辑">
            <Button
              type="text"
              icon={<CodeOutlined />}
              onClick={() => handleJsonEdit(record)}
              style={{ color: themeConfig.colors.primary }}
            >
              JSON
            </Button>
          </Tooltip>
        </Space>
      ),
    },
  ];

  const handleDownloadAll = async () => {
    try {
      await downloadAllFilesAsZip(languageFiles, generateDartFileContentForDocs);
    } catch (error) {
      console.error('下载失败:', error);
    }
  };

  // JSON编辑相关功能
  const handleJsonEdit = (language: LanguageFile) => {
    setJsonEditingLanguage(language);
    setJsonText(JSON.stringify(language.data, null, 2));
    setJsonError('');
    setIsJsonModalVisible(true);
  };

  const handleJsonChange = (value: string) => {
    setJsonText(value);
    setJsonError('');
  };

  const handleJsonApply = () => {
    if (!jsonEditingLanguage) return;

    try {
      const parsedData = JSON.parse(jsonText);
      
      // 验证JSON结构
      if (typeof parsedData !== 'object' || parsedData === null) {
        throw new Error('JSON必须是一个对象');
      }
      
      // 检查所有值都是字符串
      for (const [key, value] of Object.entries(parsedData)) {
        if (typeof value !== 'string') {
          throw new Error(`键 "${key}" 的值必须是字符串类型`);
        }
      }
      
      // 这里需要调用状态更新函数，但ReviewPage没有直接访问updateLanguageFile
      // 我们需要通过props传递这个功能
      if (onEditLanguage) {
        // 临时解决方案：先关闭模态框，然后跳转到编辑页面
        setIsJsonModalVisible(false);
        message.success('JSON数据已验证，请进入编辑页面保存更改');
        onEditLanguage(jsonEditingLanguage.code);
      }
      
      setJsonError('');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'JSON格式错误';
      setJsonError(errorMessage);
      message.error(`JSON解析失败: ${errorMessage}`);
    }
  };

  const handleJsonReset = () => {
    if (jsonEditingLanguage) {
      setJsonText(JSON.stringify(jsonEditingLanguage.data, null, 2));
      setJsonError('');
      message.info('已重置为原始数据');
    }
  };

  const handleJsonCopy = () => {
    navigator.clipboard.writeText(jsonText).then(() => {
      message.success('JSON已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  const handleJsonPaste = () => {
    navigator.clipboard.readText().then((text) => {
      setJsonText(text);
      setJsonError('');
      message.success('已粘贴JSON内容');
    }).catch(() => {
      message.error('粘贴失败');
    });
  };

  return (
    <PageContainer>
      <ContentContainer>
        <HeaderSection>
          <MainTitle level={1}>
            语言评审
          </MainTitle>
          <SubTitle>
            请仔细检查所有语言的翻译内容，确保翻译质量和完整性
          </SubTitle>
        </HeaderSection>

        <StepsContainer>
          <Steps current={1} size="small">
            <Step title="上传文件" description="文件已上传" />
            <Step title="语言评审" description="检查翻译内容" />
            <Step title="下载结果" description="生成最终文件" />
          </Steps>
        </StepsContainer>

        {/* 统计信息 */}
        <ReviewCard title="翻译统计">
          <StatisticContainer>
            <Statistic
              title="语言总数"
              value={stats.totalLanguages}
              prefix={<GlobalOutlined />}
              valueStyle={{ color: themeConfig.colors.primary }}
            />
            <Statistic
              title="翻译键总数"
              value={stats.totalKeys}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: themeConfig.colors.primary }}
            />
            <Statistic
              title="完成度"
              value={stats.completionRate.toFixed(1)}
              suffix="%"
              valueStyle={{ color: stats.completionRate === 100 ? themeConfig.colors.success : themeConfig.colors.warning }}
            />
            <Statistic
              title="有问题的语言"
              value={stats.languagesWithIssues}
              valueStyle={{ color: stats.languagesWithIssues > 0 ? themeConfig.colors.error : themeConfig.colors.success }}
            />
          </StatisticContainer>
        </ReviewCard>

        {/* 语言列表 */}
        <ReviewCard title="语言列表">
          <ActionSection>
            <Search
              placeholder="搜索语言..."
              allowClear
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
              onChange={(e) => setSearchText(e.target.value)}
            />
            <Space>
              <CustomButton
                variant="outline"
                icon={<ArrowLeftOutlined />}
                onClick={onBack}
              >
                返回
              </CustomButton>
              <CustomButton
                variant="primary"
                icon={<DownloadOutlined />}
                onClick={handleDownloadAll}
              >
                下载所有文件
              </CustomButton>
              <CustomButton
                variant="primary"
                onClick={onProceed}
              >
                完成评审
              </CustomButton>
            </Space>
          </ActionSection>

          {detectionReport && detectionReport.conflicts.length > 0 && (
            <Alert
              message="发现翻译问题"
              description={`共发现 ${detectionReport.conflicts.length} 个问题，建议在下载前修复这些问题`}
              type="warning"
              showIcon
              style={{ marginBottom: themeConfig.spacing.lg }}
            />
          )}

          <LanguageTableContainer>
            <Table
              columns={columns}
              dataSource={filteredLanguageFiles}
              rowKey="code"
              pagination={{
                pageSize: 50,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                pageSizeOptions: ['20', '50', '100', '200'],
                defaultPageSize: 50,
              }}
              scroll={{ x: 800 }}
            />
          </LanguageTableContainer>
        </ReviewCard>

        {/* 翻译详情模态框 */}
        <TranslationModal
          title={`${selectedLanguage ? getLanguageName(selectedLanguage.code) : ''} 翻译详情`}
          open={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setIsModalVisible(false)}>
              关闭
            </Button>
          ]}
          width={800}
        >
          {selectedLanguage && (
            <div>
              <div style={{ marginBottom: themeConfig.spacing.md }}>
                <Text strong>语言代码：</Text>
                <Tag color={themeConfig.colors.primary}>{selectedLanguage.code}</Tag>
                <Text strong style={{ marginLeft: themeConfig.spacing.md }}>翻译项数量：</Text>
                <Text>{Object.keys(selectedLanguage.data).length}</Text>
              </div>
              
              <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
                {Object.entries(selectedLanguage.data).map(([key, value]) => (
                  <div key={key} style={{ 
                    padding: themeConfig.spacing.sm, 
                    borderBottom: `1px solid ${themeConfig.colors.border}`,
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'flex-start'
                  }}>
                    <div style={{ flex: 1, marginRight: themeConfig.spacing.md }}>
                      <Text strong style={{ color: themeConfig.colors.text }}>
                        {key}
                      </Text>
                    </div>
                    <div style={{ flex: 2 }}>
                      <Text style={{ 
                        color: value && value.trim() !== '' ? themeConfig.colors.text : themeConfig.colors.textSecondary,
                        fontStyle: value && value.trim() !== '' ? 'normal' : 'italic'
                      }}>
                        {value && value.trim() !== '' ? value : '(空)'}
                      </Text>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </TranslationModal>

        {/* JSON编辑模态框 */}
        <Modal
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <CodeOutlined style={{ color: themeConfig.colors.primary }} />
              <span>JSON编辑 - {jsonEditingLanguage ? getLanguageName(jsonEditingLanguage.code) : ''}</span>
            </div>
          }
          open={isJsonModalVisible}
          onCancel={() => setIsJsonModalVisible(false)}
          width={800}
          footer={[
            <Button key="cancel" onClick={() => setIsJsonModalVisible(false)}>
              取消
            </Button>,
            <Button key="reset" icon={<ReloadOutlined />} onClick={handleJsonReset}>
              重置
            </Button>,
            <Button key="apply" type="primary" onClick={handleJsonApply} disabled={!!jsonError}>
              应用JSON
            </Button>
          ]}
        >
          <div>
            <div style={{ marginBottom: themeConfig.spacing.md }}>
              <Space>
                <Button
                  icon={<CopyOutlined />}
                  onClick={handleJsonCopy}
                  size="small"
                >
                  复制JSON
                </Button>
                <Button
                  onClick={handleJsonPaste}
                  size="small"
                >
                  粘贴JSON
                </Button>
              </Space>
            </div>

            {jsonError && (
              <Alert
                message="JSON格式错误"
                description={jsonError}
                type="error"
                showIcon
                style={{ marginBottom: themeConfig.spacing.md }}
              />
            )}

            <div style={{ 
              border: `1px solid ${themeConfig.colors.border}`,
              borderRadius: themeConfig.borderRadius.small,
              overflow: 'hidden'
            }}>
              <TextArea
                value={jsonText}
                onChange={(e) => handleJsonChange(e.target.value)}
                rows={15}
                placeholder="请粘贴或编辑JSON内容..."
                style={{ 
                  fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
                  fontSize: '14px',
                  lineHeight: '1.5',
                  border: 'none',
                  resize: 'vertical'
                }}
              />
            </div>

            <div style={{ 
              marginTop: themeConfig.spacing.sm,
              padding: themeConfig.spacing.sm,
              backgroundColor: themeConfig.colors.backgroundLight,
              borderRadius: themeConfig.borderRadius.small,
              fontSize: themeConfig.typography.fontSize.caption,
              color: themeConfig.colors.textSecondary
            }}>
              💡 提示：您可以粘贴其他JSON文件的键值对，系统会自动验证格式。应用后请进入编辑页面保存更改。
            </div>
          </div>
        </Modal>
      </ContentContainer>
    </PageContainer>
  );
};
